
const model = require('../schems')




let tagsAction = {

}

//查询所有tag
tagsAction.all= function(callback){
  model.tag.find({},function(err,doc){
    if(doc){
      let alltags = JSON.parse(JSON.stringify(doc))
      callback(alltags)
    }
  })
}

//跟新tag信息
tagsAction.updateById = function(_id,callback){
  model.tag.updateOne({_id},function(err,doc){
    doc&&callback(true)
  })
}

tagsAction.add = function(tag,callback){
  let newtag  = new model.tag(tag)
  newtag.save((err,doc)=>{
    doc&&callback(true)
  })
}


/**
 * 处理tag最终返回文章tagid数组
 * @param {*} _id 
 * @param {Array} newtags 
 */
tagsAction.tagChuli = async function (_id, newtags) {

  let tagsarr, oldtags = [];
  let tagsId = []
  let tagchang = {
  }

  //更新文章，有id传进来
 
  if (_id) {
    //根据文章id 得到tag 的id
    await model.article.findOne({ _id }, function (err, doc) {
      if (doc) {
        tagsarr = doc.tags //得到旧的tagid
      }
    })
  
    if (tagsarr) {
      //根据tag的id,获得tag名称
      let getTagname = function (_id) {
        return new Promise(function (resolve, reject) {
          model.tag.findOne({ _id }, function (err, doc) {
            if (doc) {
              return resolve(doc)
            }
          })
        })
      }

      await Promise
        .all(tagsarr.map(_id => getTagname(_id)))
        .then(function (result) {
          result.forEach(item => {
            oldtags.push(item.tagName)
          })
        });

     

      //比对，得到需要删除的tag和添加的tag
      tagchang = tagHandle(oldtags, newtags)
      console.log(tagchang)

      //把文章删除了的tag更新计数
      let upCount = function (name) {
        return new Promise(function (resolve, reject) {
          model.tag.findOneAndUpdate({ 'tagName': name }, { $inc: { count: -1 } }, function (err, doc) {
            if (doc) {
              return resolve(doc)
            }
          })
        })
      }

      await Promise
        .all(tagchang.delet.map(name => upCount(name)))
        .then(function (result) {
        
          tagsId = JSON.parse(JSON.stringify(tagsarr))
          result.forEach(item => {
          let index=  tagsId.findIndex(function(e){
              return e==item
            })
            tagsId.splice(index,1)
            oldtags.splice(index,1)
          })
        });

    } else {
      tagchang.add = newtags;
   
    }
  } else {
    if(newtags[0]==''){return}
    tagchang.add = newtags;
  }

  let index = tagchang.add.length
  // 把文章新增tag 
  function addt(name){
    let biaoqian = {
      tagName: name,
      count: 1
    }
    return new Promise(function(resolve,reject){
      let tag =new model.tag(biaoqian)
      tag.save().then(doc => {
        if(doc){
          resolve(doc)
        } 
      })
    })
  }
  
  function checkAdd(name) {
    //检查是否包含tag 
    return new Promise(function (resolve, reject) {
      model.tag.findOneAndUpdate({ 'tagName': name }, { $inc: { count: 1 } }, { new: true }, function (err, doc) {
        if (doc) {
          resolve(doc)//resolve只能传递一个值 坑了我好久
        }else{
          //console.log('这里是数组11',name)
          resolve(name)
        } 
      })
    })
  } 
  await Promise
    .all(tagchang.add.map(name => checkAdd(name)))
    .then(function (result) {
        let needadd = []
        let needup =[]

        result.forEach(item=>{
          if(typeof item == 'string'){
            needadd.push(item)
          }else{
            needup.push(item)
          }
        })

        needup.forEach(item=>{
          tagsId.push(item._id)
          oldtags.push(item.tagName)
        })

      return Promise
      .all(needadd.map(e=>addt(e)))

      }).then(function(e){
        e.forEach(item=>{
          tagsId.push(item._id)
          oldtags.push(item.tagName)
        })
      })
      
    return {
      tagsId,
      oldtags
    };
}

/**
 * 数组比较，返回旧数组在新数组中不存在的元素与新数组和旧数组相同的元素
 * @param {*} oldArr 
 * @param {*} newArr 
 * @return {object} 
 */
function tagHandle(oldArr, newArr) {
  let add = [];
  let delet = [];
 
  if (newArr[0]!=='') {
    for (let i = 0; i <= oldArr.length - 1; i++) {
      if (newArr.indexOf(oldArr[i]) == -1) {
        delet.push(oldArr[i])
      }
    }
    for (let i = 0; i <= newArr.length - 1; i++) {
      if (oldArr.indexOf(newArr[i]) == -1) {
        add.push(newArr[i])
      }
    }

  } else {
    delet = oldArr
  }
  
  return tagchang = {
    add,
    delet
  }
}

module.exports = tagsAction
